<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/categories' }"><a href="/">商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- 提示信息区域 -->
             <el-alert show-icon type="info" center  title="添加商品信息" :closable="false">
            </el-alert>
            <!-- 状态步骤条 -->
            <el-steps :space="200" :active="activeIndex - 0" finish-status="success"
            style="margin-top:15px" align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
            </el-steps>
            <!-- 左边侧边栏区域 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
            <el-tabs v-model="activeIndex" tab-position="left" name="0" :before-leave="beforeTabLeave" @tab-click="tabClicked">
                <el-tab-pane label="基本信息">
                    <el-form-item label="商品名称" prop="goods_name">
                        <el-input v-model="addForm.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="goods_price">
                        <el-input v-model="addForm.goods_price" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品重量" prop="goods_weight">
                        <el-input v-model="addForm.goods_weight" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="goods_number">
                        <el-input v-model="addForm.goods_number" type="number"></el-input>
                    </el-form-item>
                      <el-form-item label="商品分类" prop="">
                          <el-cascader expand-trigger="hover" 
                          :options="cateList" :props="cateProps"
                          v-model="addForm.goods_cat"
                          @change="handleChange"
                          :show-all-levels="false">

                          </el-cascader>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                    <el-form-item  v-for="item in  addForm.manyAttr" :key="item.attr_id"
                    :label="item.attr_name">
                        <el-checkbox-group v-model="item.attr_vals">
                            <el-checkbox :label="checkname" v-for="(checkname, i) in item.attr_vals" :key="i" border>
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                    <el-form-item 
                    :label="item.attr_name"
                    v-for="item in addForm.onlyAttr" :key="item.attr_id">
                        <el-input v-model="item.attr_vals"></el-input>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                    <el-upload
                        :action="uploadUrl"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :file-list="addForm.fileList"
                        list-type="picture" :headers="headerObj" :on-success="handleSuccess">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                      <quill-editor v-model="addForm.goods_introduce">
                    </quill-editor>
                    <el-button  type="primary" @click="addGood">商品提交</el-button>
                </el-tab-pane>
            </el-tabs>
            </el-form>
        </el-card>
        <!-- 图片预览 -->
        <el-dialog
        title="图片预览"
        :visible.sync="previewDialog"
        width="50%"
        >
            <img :src="previewPath" style="width:100%;height:350px">
        </el-dialog>
    </div>
</template>

<script>
export default {
    
    data(){
    return{
        
        activeIndex:0,
    //    添加商品信息表单对象
        addForm:{
            goods_name:'',
            goods_price:0,
            goods_weight:0,
            goods_number:0,
            goods_cat:[],
            manyAttr:[],
            onlyAttr:[],
            fileList:[],
            pics:[],
            // 商品的详情描述
            goods_introduce:'',
            attrs:[]

        },
        //提交图片地址
        uploadUrl:'https://www.liulongbin.top:8888/api/private/v1/upload',
         //添加商品表单的验证规则
        addFormRules:{
            goods_name:[
            {required:true,message:'请输入商品名称',trigger:'blur'}
        ],goods_price:[{
            required:true,message:'请输入商品价格',trigger:'blur'
        }],goods_weight:[{
             required:true,message:'请输入商品重量',trigger:'blur'
        }],goods_number:[{
             required:true,message:'请输入商品数量',trigger:'blur'
        }],goods_cat:[{
            required:true,message:'请选择商品分类',trigger:'blur'
        }]
        },
        // 商品所有分类数据
        cateList:[],
        cateProps:{
          label: 'cat_name',
          value: 'cat_id',
          children: 'children'

        },
        headerObj:{
            Authorization: window.sessionStorage.getItem('token') || ''
        },
        previewPath:'',
        previewDialog:false
    }
    },
    created(){
        this.getCateList()
    },
    methods:{
        async getCateList(){
            const { data :res } = await this.$http.get(`categories`)

            if(res.meta.status !==200) return this.$message.error(res.meta.msg)

            this.cateList = res.data
            console.log(this.cateList);
            
        },
        // 级联选择器发生变化触发这个函数
        handleChange(){
            if(this.addForm.goods_cat.length !==3){
                this.addForm.goods_cat = []
            }
            
        },
        beforeTabLeave(activeName,oldActiveName){
           if(oldActiveName === '0' && this.addForm.goods_cat.length !== 3){
               this.$message.error('请选择商品分类')
               return false
           }
        },
        async tabClicked(){
            if(this.activeIndex === '1'){
               const { data: res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                   params:{
                       sel:'many'
                   }
               })
               if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

               res.data.forEach(item => {
                   item.attr_vals = item.attr_vals ? item.attr_vals.split(' '):[]
               })
                this.addForm.manyAttr = res.data
        }else if(this.activeIndex === '2'){
            const { data: res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                   params:{
                       sel:'only'
                   }
               })
               if(res.meta.status !== 200) {return this.$message.error(res.meta.msg)}

                this.addForm.onlyAttr = res.data
                console.log(this.addForm.onlyAttr);                        
}
        },
        // 点击图片预览事件
        handlePreview(file){      
            this.previewPath = file.response.data.url
            this.previewDialog = true
        },
        //图片删除功能
        handleRemove(file){
            let i= this.addForm.pics.findIndex(function (item) {
              return  item.pic === file.response.data.tem_path
            })
            this.addForm.pics.splice(i,1)
            console.log(this.addForm.pics);
            
        },
        handleSuccess(response){
            // 1.拼接得到一个图片信息对象
            const picInfo = { pics: response.data.tmp_path}
            // 2.将图片信息对象，push到pics数组中
            this.addForm.pics.push(picInfo)
            console.log(this.addForm.pics);
            
        },
        addGood(){
            console.log(this.addFormRules);
            this.$refs.addFormRef.validate(async (valid) =>{
                if(valid){
                    //执行添加的业务逻辑
                    //lodash包调用cloneDeep(obj)对obj进行深拷贝
                    // 一个组件需要一直使用数组模式的数据，但提交的时候是需要传一个字符串上去，所以只能使用深拷贝将此数组数据拷贝出来一个数组数据然后再对这个拷贝数据进行操作
                    const obj = _.cloneDeep(this.addForm)
                    obj.goods_cat = obj.goods_cat.toString()
                    
                    obj.manyAttr.forEach(item =>{
                        let newInfo = {
                            attr_id: item.attr_id,
                            attr_value: item.attr_vals.toString()
                        }
                        obj.attrs.push(newInfo)
                    })
                     obj.onlyAttr.forEach(item =>{
                        let newInfo = {
                            attr_id: item.attr_id,
                            attr_value: item.attr_vals.toString()
                        }
                        obj.attrs.push(newInfo)
                    })


                    delete obj.fileList
                    delete obj.manyAttr
                    delete obj.onlyAttr
                    console.log(obj.attrs);
                    

                    //发起请求添加商品数据
                    //要求商品名称name为唯一
                    const { data: res} = await this.$http.post(`goods`,obj)
                    if(res.meta.status !== 201) return this.$message.success(res.meta.msg)
                    this.$router.push('/goods')
               }else{
                    return this.$message.error('请填写完整商品信息')
                }
            })
        }
    },
    computed:{
        cateId(){
            return this.addForm.goods_cat[2]
        }
    }
}
</script>

<style lang="less">
        .el-checkbox{
            margin-right:10px !important;
        }
        .ql-editor{
            height:200px !important;
        }
</style>